from django.db.transaction import atomic
from django.http import HttpRequest, HttpResponse, JsonResponse
from django.shortcuts import render
from django.db import DatabaseError
from django.db.models import Q
from django.utils import timezone
from rest_framework.decorators import api_view
from rest_framework.response import Response
from rest_framework.viewsets import ModelViewSet

from course2.serializers import CourseSerializer, CourseSimpleSerializer, CommentSerializer, TeacherSerializer, \
    ChapterSerializer
from education.models import Course, Comment, Teacher, Order, User, Chapter, Sturecord

#1
class CourseViewSet(ModelViewSet):
    # 显示所有课程
    queryset = Course.objects.all()
    serializer_class = CourseSimpleSerializer

#2
class TeacherViewSet(ModelViewSet):
    # 显示所有老师
    queryset = Teacher.objects.all()
    serializer_class = TeacherSerializer

# @api_view(('GET',)) # FBV基于函数的视图 ---> 高度定制，自动@csrf_exempt
# def show_courses(request: HttpRequest) -> HttpResponse:
#     # 显示所有课程
#     queryset = Course.objects.only('couname', 'image','stu_count').all()
#     data = CourseSimpleSerializer(queryset, many=True).data
#     return Response({'courses': data})

#3
@api_view(('GET',))
def show_coudet(request: HttpRequest) -> HttpResponse:
    # 显示某门课程详情和对应的所有老师简介
    cno = int(request.GET['cno'])
    queryset = Course.objects.get(couid=cno)
    data = CourseSerializer(queryset).data
    queryset2 = Teacher.objects.filter(course=cno)
    data2 = TeacherSerializer(queryset2,many=True).data
    return Response({'coudet': data,'teachers':data2})
#4
@api_view(('GET',))
def show_coucomments(request: HttpRequest) -> HttpResponse:
    # 显示某门课程所有评价
    cno = int(request.GET['cno'])
    queryset = Comment.objects.filter(course=cno)
    data = CommentSerializer(queryset,many=True).data
    return Response({'comments': data})

#5
@api_view(('POST','GET'))
def show_chapters(request: HttpRequest) -> HttpResponse:
    # 查看课程所有章节
    username = request.data.get('unam')
    couid = int(request.data.get('cno'))
    uid = User.objects.get(username=username).userid
    queryset = Chapter.objects.filter(course__couid=couid).order_by('-chapterno')[::-1]
    data = ChapterSerializer(queryset,many=True).data
    if Order.objects.filter(Q(user__userid=uid)&Q(is_pay=1)&Q(couid=couid)):
        # 有购买记录返回本课程所有章节的视频
        return Response({'chapters':data})
    else:
        # 没有购买记录只返回第一个章节的视频(试看)
        return Response({'chapters': data[:1]})

#6
@api_view(('POST',))
def add_comment(request: HttpRequest) -> HttpResponse:
    # 添加评论
    username = request.data.get('unam')
    content = request.data.get('cnt')
    couid = request.data.get('cid')
    try:
        user= User.objects.get(username=username)
        course = Course.objects.get(couid=couid)
        new_com = Comment()
        new_com.username = username
        new_com.course = course
        new_com.user = user
        new_com.content = content
        new_com.make_time = timezone.now()
        new_com.save()
        data = {'code':1000,'message':'发表评论成功'}
    except (User.DoesNotExist,Course.DoesNotExist,ValueError):
        data = {'code':1001,'message':'发表评论失败，用户或课程不存在!'}
    return Response(data)
#7
@api_view(('GET','POST'))
def del_comment(request: HttpRequest) -> HttpResponse:
    # 删除评论
    commid = request.data.get('cmid')
    username = request.data.get('unam')
    try:
        user = User.objects.get(username=username)
        Comment.objects.get(Q(commid=commid)&Q(user=user)).delete()
        data = {'code': 2000, 'message': '删除评论成功'}
    except (Comment.DoesNotExist,User.DoesNotExist,ValueError):
        data = {'code':2001,'message':'删除评论失败，该评论不属于此用户或不存在'}
    return Response(data)

#8
@api_view(('POST',))
def gen_sturecord(request: HttpRequest) -> HttpResponse:
    # 生成学习记录
    chaid = request.data.get('chaid')
    username = request.data.get('unam')
    couid = request.data.get('cid')
    try:
        chapter = Chapter.objects.get(chaid=chaid)
        user = User.objects.get(username=username)
        course = Course.objects.get(couid=couid)
        record = Sturecord.objects.filter(Q(user=user)&Q(chapter=chapter)).first()
        if record:
            # 同一用户，同一章节学习记录存在，只更改最后学习时间
            record.make_time = timezone.now()
            record.save()
            data = {'code':3001,'message':'更改学习记录最后时间成功'}
        else:
            # 学习记录不存在新增学习记录
            new_record = Sturecord()
            new_record.user = user
            new_record.chapter = chapter
            new_record.course = course
            new_record.make_time = timezone.now()
            new_record.save()
            data = {'code':3000,'message':'新增学习记录成功'}
    except (ValueError,Chapter.DoesNotExist,User.DoesNotExist,Course.DoesNotExist):
        data = {'code': 3002, 'message': '请求参数有误，课程章节/用户名/课程不存在!'}
    return Response(data)

#9
@api_view(('POST','GET'))
def del_sturecord(request: HttpRequest) -> HttpResponse:
    # 删除学习记录
    chaid = request.data.get('chaid')
    username = request.data.get('unam')
    try:
        user = User.objects.get(username=username)
        record = Sturecord.objects.filter(Q(chapter=chaid)&Q(user=user)).first()
        if record:
            record.delete()
            data = {'code':3003,'message':'学习记录删除成功'}
        else:
            data = {'code': 3004, 'message': '该条学习记录已不存在'}
    except (ValueError,KeyError,User.DoesNotExist,Sturecord.DoesNotExist):
        data = {'code': 3005, 'message': '求情参数有误，章节/用户名不存在'}
    return Response(data)

#10
@api_view(('POST',))
def gen_order(request: HttpRequest) -> HttpResponse:
    # 下订单
    username = request.data.get('unam')
    couid = request.data.get('cid')
    pay_type = request.data.get('ptype')
    try:
        user = User.objects.only('userid').get(username=username)
        if pay_type not in ('wx_pay','alipay','balance'):
            data = {'code':4001,'message':'暂未接入该支付方式，订单创建失败'}
            return Response(data)
        if Order.objects.filter(Q(couid=couid)&Q(user=user)).first():
            data = {'code':4002,'message':'你已有该课程的订单，无需重复下单'}
            return Response(data)
        course = Course.objects.get(couid=couid)
        new_order = Order()
        new_order.couid = couid
        new_order.goods_name = course.couname
        new_order.price = course.price
        new_order.make_time = timezone.now()
        new_order.pay_type = pay_type
        new_order.user = user
        new_order.save()
        data = {'code':4000,'message':'订单创建成功，请刷新页面'}
    except (KeyError,ValueError,Course.DoesNotExist,User.DoesNotExist):
        data = {'code':4003,'message':'请求参数有误，用户/课程不存在'}
    return Response(data)

#11
@api_view(('GET',))
def go_pay(request: HttpRequest) -> HttpResponse:
    orderno = request.GET.get('ordno')
    goods_name = request.GET.get('gdsnam')
    username = request.GET.get('unam')
    pay_type = request.GET.get('ptype')
    try:
        price = Order.objects.get(orderid=orderno).price
        if Order.objects.get(orderid=orderno).is_pay == True:
            return Response({'code': 5003, 'message': '该订单已支付，请勿重复提交支付请求!'})
        if pay_type == 'wx_pay':
            pass
            """
            调用微信支付接口，传入订单，价格，商品名称,跳转到支付页面，添加异步任务
            返回支付成功就修改订单的is_pay为True，并修改支付时间
            """
        elif pay_type == 'alipay':
            pass
            """
            调用支付宝接口，传入订单，价格，商品名称，跳转到支付页面，添加异步任务
            返回支付成功就修改订单的is_pay为True，并修改支付时间
            """
        elif pay_type == 'balance':
            user = User.objects.get(username=username)
            order = Order.objects.get(orderid=orderno)
            if user.balance >= price:
                user.balance -= price
                user.point += price
                order.is_pay = True
                with atomic():
                    user.save()
                    order.save()
                return Response({'code':5000,'message':'订单支付成功，请返回刷新"我的订单"!'})
            else:
                return Response({'code':5001,'message':'余额不足，支付失败!'})
    except (ValueError,Order.DoesNotExist,User.DoesNotExist):
        return Response({'code': 5004, 'message': '请求参数有误,用户/订单不存在'})